﻿using CSCommonUtils;
using CsharpHttpHelper;
using Newtonsoft.Json;
using System;
using System.Net;
using System.Text;
using System.Timers;

namespace FX_API
{
    public class FenxiangAPI
    {
        /// <summary>
        /// 初始化纷享API Token，并启动一个线程去定时刷新Token
        /// </summary>
        public static bool Init()
        {
            var resp = FetchToken();
            if (!resp.IsSucess)
            {
                return false;
            }

            AccessToken token = JsonConvert.DeserializeObject<AccessToken>(resp.Message);
            StartTokenRefreshTimer(token.expiresIn);

            return true;
        }

        private static void StartTokenRefreshTimer(int expiresIn)
        {
            Timer tokenRefreshTimer = new Timer
            {
                Interval = expiresIn,
                Enabled = true
            };

            tokenRefreshTimer.Elapsed += (object sender, ElapsedEventArgs args) =>
            {
                var resp = FetchToken();
                AccessToken token = JsonConvert.DeserializeObject<AccessToken>(resp.Message);
                tokenRefreshTimer.Interval = token.expiresIn;
            };

            tokenRefreshTimer.Start();
        }

        /// <summary>
        /// 初始化获取企业令牌
        /// </summary>
        public static ResultMessage FetchToken()
        {
            HttpHelper Inithelper = new HttpHelper();
            HttpItem postitem = new HttpItem
            {
                URL = "https://open.fxiaoke.com/cgi/corpAccessToken/get/V2",

                ContentType = "application/json",
                Postdata = "{\"appId\": \"" + appId + "\",\"appSecret\":\"" + appSecret + "\",\"permanentCode\":\"" + permanentCode + "\"}",
                PostEncoding = Encoding.UTF8,
                Method = "POST",
                Accept = "application/json"
            };
            try
            {

                HttpResult html = Inithelper.GetHtml(postitem);
                //获得lotteryCode
                if (html.StatusCode == HttpStatusCode.OK)
                {
                    AccessToken ts = JsonConvert.DeserializeObject<AccessToken>(html.Html);
                    if (ts.errorCode == 0)
                    {
                        corpAccessToken = ts.corpAccessToken;
                        corpId = ts.corpId;
                        return new ResultMessage() { IsSucess = true, Message = html.Html };
                    }
                    else
                    {
                        return new ResultMessage() { IsSucess = false, Message = html.Html };
                    }
                }
                else
                {
                    return new ResultMessage() { IsSucess = false, Message = html.Html };
                }

            }
            catch (Exception ex)
            {
                return new ResultMessage() { IsSucess = false, Message = ex.Message };
            }
        }

        /// <summary>
        /// 向用户发送企信消息
        /// </summary>
        /// <param name="obj"></param>
        public static void SendMessage(object obj)
        {
            HttpHelper helper = new HttpHelper();
            HttpItem postitem = new HttpItem
            {
                URL = "https://open.fxiaoke.com/cgi/message/send",
                ContentType = "application/json",
                Postdata = JsonConvert.SerializeObject(obj),
                PostEncoding = Encoding.UTF8,
                Method = "POST",
                Accept = "application/json"
            };
            helper.GetHtml(postitem);
        }

        public class AccessToken
        {
            public int errorCode { get; set; }
            public string errorMessage { get; set; }
            public string corpAccessToken { get; set; }
            public string corpId { get; set; }
            public int expiresIn { get; set; }
        }

        public static string corpId { get; set; }
        public static string corpAccessToken { get; set; }
        public static readonly string appId = System.Configuration.ConfigurationManager.AppSettings["appId"];
        public static readonly string appSecret = System.Configuration.ConfigurationManager.AppSettings["appSecret"];
        public static readonly string permanentCode = System.Configuration.ConfigurationManager.AppSettings["permanentCode"];
        public static readonly string openUserId = System.Configuration.ConfigurationManager.AppSettings["openUserId"];
        public static readonly string NoticeUserId = System.Configuration.ConfigurationManager.AppSettings["NoticeUserId"];

        public static readonly string customizedQueryURL = "https://open.fxiaoke.com/cgi/crm/custom/data/query";
        public static readonly string presetQueryURL = "https://open.fxiaoke.com/cgi/crm/v2/data/query";
        public static readonly string customizedCreateURL = "https://open.fxiaoke.com/cgi/crm/custom/data/create";
        public static readonly string presetCreateURL = "https://open.fxiaoke.com/cgi/crm/v2/data/create";
        public static readonly string customizedUpdateURL = "https://open.fxiaoke.com/cgi/crm/custom/data/update";
        public static readonly string presetUpdateURL = "https://open.fxiaoke.com/cgi/crm/v2/data/update";
    }
}
